package hibernate;

import hibernate.entities.Piece;
import hibernate.entities.User;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.FlushModeType;
import javax.persistence.Query;

import sun.reflect.ReflectionFactory.GetReflectionFactoryAction;

public class PieceDAO {
	static PieceDAO instance = null;
	EntityManager em;
	private EntityManagerFactory emf;
	
	public static PieceDAO getInstance(EntityManagerFactory emf){
		if (instance == null){
			instance = new PieceDAO(emf);
		}
		return instance;
	}
	
	private PieceDAO(EntityManagerFactory emf){
		this.emf = emf;
		em = emf.createEntityManager();
	}
	
	public void create(String nom, Piece nord, Piece sud, Piece est, Piece ouest){
		em.getTransaction().begin();
		Piece p = new Piece(nom, nord, sud, est, ouest);
		em.persist(p);
		em.getTransaction().commit();
	}
	
	public Piece get(int id){
		em.getTransaction().begin();
		Query query = em.createQuery("SELECT p FROM Piece p WHERE p.id = "+id);
		Piece p = (Piece) query.getSingleResult();
		em.getTransaction().commit();
		return p;
	}
	
	@SuppressWarnings("unchecked")
	public List<User> getAllUsers(int pieceId){
		em.clear();
		Query query = em.createNativeQuery("SELECT u.id, u.identifiant, u.sexe, u.nom, u.taille, u.humeur, u.connecte, u.fk_piece FROM Piece p, User u WHERE p.id = u.fk_piece AND p.id = ?", User.class);
		query.setParameter(1, pieceId);
		return (List<User>) query.getResultList();
	}
	
}

